package com.peng.mybatis.io;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Arrays;
import java.util.Objects;

public class Resources {

    public static Reader getResourceAsReader(String resource) {
        return new InputStreamReader(getResourceAsStream(resource));
    }

    private static InputStream getResourceAsStream(String resource) {
        return Arrays.stream(getClassLoaders())
                .map(classLoader -> classLoader.getResourceAsStream(resource))
                .filter(Objects::nonNull)
                .findAny()
                .orElseThrow(() -> new RuntimeException("资源不存在: " + resource));
    }

    private static ClassLoader[] getClassLoaders() {
        return new ClassLoader[]{
                ClassLoader.getSystemClassLoader(),
                Thread.currentThread().getContextClassLoader(),
        };
    }

    public static Class<?> classForName(String className) throws ClassNotFoundException {
        return Class.forName(className);
    }

}